/* 
 * File:   ConnTcpip.cpp
 * Author: kisme
 * 
 * Created on 26 December 2012, 10:27 PM
 */

#include "ConnTcpip.h"

ConnTcpip::ConnTcpip() {
    this->mConf = new Conf_ConnTcpip();
}

ConnTcpip::ConnTcpip(const ConnTcpip& orig) {
}

ConnTcpip::~ConnTcpip() {
    
}

/**
 * 配置静态数据,基础数据
 * @return 
 */
int ConnTcpip::config()
{
    this->mConf->port = 8555;
    this->mConf->queue = 1500;
    this->mConf->addr_in = new sockaddr_in();
    
    bzero(this->mConf->addr_in,sizeof(*(this->mConf->addr_in)));
    this->mConf->addr_in->sin_family = AF_INET;
    this->mConf->addr_in->sin_port = htons(8555);
    this->mConf->addr_in->sin_addr.s_addr = htons(INADDR_ANY);
    
    this->mConf->len = sizeof(*(this->mConf->addr_in));
    return 0;
}

int ConnTcpip::bindPort()
{
    int _result = RESULT_FAI;
    if ((this->mConf->fd = socket(AF_INET,SOCK_STREAM,0)) < 0)
    {
       printf("create socket error!\n");
       exit(1);
    }

    printf(":::The New Socketfd: %d \n", this->mConf->fd);
    printf(":::Bind Port: %d \n", this->mConf->port);

    if (bind(this->mConf->fd,(struct sockaddr*)this->mConf->addr_in, this->mConf->len)<0)
    {
        printf("bind to port %d failure!\n", this->mConf->port);
        exit(1);
    }
    else
    {
        _result = RESULT_SUC;
        printf(":::Socket is ok .... \n"); 
    }
    return _result;
}

int ConnTcpip::listenPort()
{
    int _result = RESULT_FAI;
    printf("Socket Listen...Start..\n");
    if (listen(this->mConf->fd, this->mConf->queue) < 0)
    {
        printf("call listen failure!\n");
        exit(1);
    }
    else
    {
        _result = RESULT_SUC;
        fprintf(stdout, "Socket Listen...Finish..\n");
    }
    return _result;
}

int ConnTcpip::nonBlock()
{
    this->setNonblock(this->mConf->fd);
    return 0;
}

int ConnTcpip::getSockFd()
{
    return this->mConf->fd;
}